<?php
class ModelCatalogTopic extends Model{
    public function getAllowedForums($forum_id_str) {
        if($forum_id_str){
            $encrypt_data=md5($forum_id_str);

            $query=$this->sql_cache->get('topic.allowedforums.' . $encrypt_data);

            if(!$query){
                $query = $this->db->query("SELECT f.forum_id, f.topic_category_enabled, n.forum_name FROM " . DB_PREFIX . "community_forum AS f LEFT JOIN " . DB_PREFIX . "community_forum_name_des_rule AS n ON (n.forum_id=f.forum_id AND n.language_id = '" . (int)$this->config->get('config_language_id') . "') WHERE f.forum_id IN (" . $forum_id_str . ") ORDER BY f.sort_order_id ASC, n.forum_name ASC");

                $this->sql_cache->set('topic.allowedforums.' . $encrypt_data,$query,TRUE);
            }

            return $query->rows;
        }else{
            return array();
        }
    }

    public function getTopicCategories($getData){
        $encrypt_data=md5($getData['forum_id']);

        $query=$this->sql_cache->get('topic.topiccategories.' . $encrypt_data . '.' . (int)$this->config->get('config_language_id'));

        if(!$query){
            $query=$this->db->query("SELECT topic_category_id, topic_category_title FROM " . DB_PREFIX . "community_topic_category WHERE forum_id='" . (int)$getData['forum_id'] . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY sort_order_id ASC, topic_category_title ASC");

            $this->sql_cache->set('topic.topiccategories.' . $encrypt_data . '.' . (int)$this->config->get('config_language_id'),$query,TRUE);
        }

        return $query->rows;
    }

    public function getTotalTopicsByProductId($product_id){
        $encrypt_data=md5($product_id);

        $query=$this->sql_cache->get('topic.totaltopicsbyproductid.' . $encrypt_data);

        if(!$query){
            $query=$this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "community_topics WHERE cart_product_id='" . (int)$product_id . "' AND topic_approved='1' AND topic_deleted='0'");

            $this->sql_cache->set('topic.totaltopicsbyproductid.' . $encrypt_data,$query,TRUE);
        }

        return $query->row['total'];
    }

    public function getTopicsByProductId($product_id,$start,$limit){
        $encrypt_data=md5($product_id);

        $query=$this->sql_cache->get('topic.topicsbyproductid.' . $encrypt_data . '.' . $start . '-' . $limit);

        if(!$query){
            $query=$this->db->query("SELECT * FROM " . DB_PREFIX . "community_topics WHERE cart_product_id='" . (int)$product_id . "' AND topic_approved='1' AND topic_deleted='0' ORDER BY topic_time DESC LIMIT " . (int)$start . "," . (int)$limit);

            $this->sql_cache->set('topic.topicsbyproductid.' . $encrypt_data . '.' . $start . '-' . $limit, $query, TRUE);
        }

        return $query->rows;
    }

    public function addTopic($product_id,$postData){
        $this->db->query("INSERT INTO " . DB_PREFIX . "community_topics SET forum_id='" . (int)$postData['forum'] . "', cart_product_id='" . (int)$product_id . "', topic_category_id='" . (int)$postData['topic-category'] . "', topic_approved='1', topic_title='" . $this->db->escape($postData['subject']) . "', topic_poster_id='" . (int)$this->customer->getForumUserId() . "', topic_time='" . time() . "', topic_first_poster_name='" . $this->db->escape($this->customer->getForumUserName()) . "', topic_last_poster_id='" . (int)$this->customer->getForumUserId() . "',topic_last_poster_name='" . $this->db->escape($this->customer->getForumUserName()) . "', topic_last_post_subject='" . $this->db->escape($postData['subject']) . "', topic_last_post_time='" . time() . "'");

        $topic_id=$this->db->getLastId();

        $this->db->query("INSERT INTO " . DB_PREFIX . "community_posts SET topic_id='" . (int)$topic_id . "', forum_id='" . (int)$postData['forum'] . "', poster_id='" . (int)$this->customer->getForumUserId() . "',poster_ip='" . $this->db->escape($this->request->server['REMOTE_ADDR']) . "', post_time='" . time() . "', post_approved='1', post_username='" . $this->db->escape($this->customer->getForumUserName()) . "', post_subject='" . $this->db->escape($postData['subject']) . "', post_text='" . $this->db->escape($postData['content']) . "'");

        $post_id=$this->db->getLastId();

        $this->db->query("UPDATE " . DB_PREFIX . "community_topics SET topic_first_post_id='". (int)$post_id . "', topic_last_post_id='" . (int)$post_id . "' WHERE topic_id='" . (int)$topic_id . "'");

        $notifyMe=isset($postData['notify']) ? TRUE : FALSE;

        //topic subscription
        if($notifyMe){
            $this->db->query("INSERT INTO " . DB_PREFIX . "community_topic_notify SET user_id='" . (int)$this->customer->getForumUserId() . "', topic_id='" . (int)$topic_id . "'");
        }

        //update user's num of topics and posts
        $this->db->query("UPDATE " . DB_PREFIX . "community_users SET user_topics=user_topics+1, user_posts=user_posts+1, user_lastpost_time='" . time() . "' WHERE user_id='" . (int)$this->customer->getForumUserId() . "'");

        //update relative field values of forum
        $this->db->query("UPDATE " . DB_PREFIX . "community_forum SET forum_posts=forum_posts+1, forum_topics=forum_topics+1, forum_last_post_id='" . $post_id . "', forum_last_poster_id='" . (int)$this->customer->getForumUserId() . "', forum_last_post_subject='" . $this->db->escape($postData['subject']) . "', forum_last_post_time='" . time() . "', forum_last_poster_name='" . $this->db->escape($this->customer->getForumUserName()) . "' WHERE forum_id='" . (int)$postData['forum'] . "'");

        //update forum statics data
        $this->db->query("UPDATE " . DB_PREFIX . "setting SET `value`=`value`+1 WHERE `key`='total_topics'");
        $this->db->query("UPDATE " . DB_PREFIX . "setting SET `value`=`value`+1 WHERE `key`='total_posts'");

        $this->sendForumNewTopicNotification($postData,$postData['subject'],$topic_id);
        $this->UpdateUserRank();

        $encrypt_data=md5($product_id);
        $this->sql_cache->delete('topic.totaltopicsbyproductid.' . $encrypt_data);
        $this->sql_cache->delete('topic.topicsbyproductid.' . $encrypt_data);
    }

    private function sendForumNewTopicNotification($data,$topicTitle,$topicId){
        $query=$this->db->query("SELECT fn.user_id, u.user_email FROM " . DB_PREFIX . "community_forum_notify AS fn LEFT JOIN " . DB_PREFIX . "community_users AS u ON (fn.user_id=u.user_id) WHERE fn.forum_id='" . (int)$data['forum'] . "' AND fn.notify_status='0' AND (fn.user_id>'" . (int)$this->customer->getForumUserId() . "' OR fn.user_id<'" . (int)$this->customer->getForumUserId() . "')");

        $forumInfo=$this->getForumInfo($data);

        foreach($query->rows as $result){
            if(isset($result['user_id'])){
                //send mails
                $this->language->load('community/post');

                $subject = sprintf($this->language->get('text_forum_topic_subject'), $forumInfo['forum_name']);

                $message = sprintf($this->language->get('text_forum_topic_content'), $forumInfo['forum_name'], $this->config->get('config_name'), $topicTitle) . "\n\n";
                $message .= $this->language->get('text_forum_topic_view_topic') . "\n";
                $message .=$this->url->link('community/viewtopic', 'fid=' . $data['forum'] . '&tid=' . $topicId, 'SSL') . "\n\n";
                $message .= $this->language->get('text_forum_topic_view_forum') . "\n";
                $message .=$this->url->link('community/viewforum', 'fid=' . $data['forum'], 'SSL') . "\n\n";
                $message .= $this->language->get('text_forum_topic_thanks') . "\n";
                $message .= $this->config->get('config_name') . "\40" . $this->language->get('text_forum_topic_team');

                $mail = new Mail();
                $mail->protocol = $this->config->get('config_mail_protocol');
                $mail->parameter = $this->config->get('config_mail_parameter');
                $mail->hostname = $this->config->get('config_smtp_host');
                $mail->username = $this->config->get('config_smtp_username');
                $mail->password = $this->config->get('config_smtp_password');
                $mail->port = $this->config->get('config_smtp_port');
                $mail->timeout = $this->config->get('config_smtp_timeout');
                $mail->setTo($result['user_email']);
                $mail->setFrom($this->config->get('config_community_email'));//to-do: ad communit_email in the admin end
                $mail->setSender($this->config->get('config_name') . "\40" . $this->language->get('text_forum_topic_team'));
                $mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
                $mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
                $mail->send();

                // update community_forum_notify record
                $this->db->query("UPDATE " . DB_PREFIX . "community_forum_notify SET notify_status='1' WHERE forum_id='" . (int)$data['forum'] . "' AND user_id='" . (int)$result['user_id'] . "'");
            }
        }
    }

    private function getForumInfo($data){
        $encrypt_data=md5($data['forum']);

        $query=$this->sql_cache->get('post.foruminfo.' . $encrypt_data . '.' . (int)$this->config->get('config_language_id'));

        if(!$query){
            $query=$this->db->query("SELECT fn.forum_name, f.forum_type, f.forum_enabled, f.topic_category_enabled FROM " . DB_PREFIX . "community_forum AS f LEFT JOIN " . DB_PREFIX . "community_forum_name_des_rule AS fn ON (fn.forum_id=f.forum_id AND fn.language_id='" . (int)$this->config->get('config_language_id') . "') WHERE f.forum_id=" . $data['forum'] . " LIMIT 0,1");

            $this->sql_cache->set('post.foruminfo.' . $encrypt_data . '.' . (int)$this->config->get('config_language_id'),$query);
        }

        return $query->row;
    }

    private function UpdateUserRank(){
        $query=$this->db->query("SELECT rank_min FROM " . DB_PREFIX . "community_ranks WHERE rank_id>'" . (int)$this->customer->getForumUserRank() . "' LIMIT 0,1");
        if(!empty($query->row) && $this->customer->getForumUserType()==5 && $this->customer->getForumUserPosts()>=$query->row['rank_min']){
            $this->db->query("UPDATE " . DB_PREFIX . "community_users SET user_rank='" . (int)$query->row['rank_id'] . "' WHERE user_id='" . (int)$this->customer->getForumUserId() . "'");
        }
    }
}
?>